﻿using UnityEngine;
using System.Collections;
using UnityEngine.Networking;

public class PlayerControl : NetworkBehaviour {
    public int moveSpeed = 10;
    public int rotateSpeed = 120;

    public Transform gunPos;
    public GameObject bulletPrefab;

    public override void OnStartLocalPlayer()
    {
        base.OnStartLocalPlayer();
        GetComponent<MeshRenderer>().material.color = Color.blue;
        GetComponent<NetworkTransform>().sendInterval = 0.015f;
    }

    // Update is called once per frame
    void Update ()
    {
        if(isLocalPlayer == false)
        {
            return;
        }
        float move = Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime;
        float rotate = Input.GetAxis("Horizontal") * rotateSpeed * Time.deltaTime;

        transform.Rotate(Vector3.up * rotate);
        transform.Translate(Vector3.forward * move);

        if(Input.GetKeyDown(KeyCode.Space))
        {
            CmdFire();
        }
    }

    [Command]
    void CmdFire()
    {
        GameObject bullet = Instantiate(bulletPrefab, gunPos.position, gunPos.rotation) as GameObject;
        bullet.GetComponent<Rigidbody>().velocity = -bullet.transform.forward * 10;
        Destroy(bullet, 2);

        NetworkServer.Spawn(bullet);
    }

}
